package com.artisan.admin.controllers;

import com.artisan.admin.model.roleViewModels.RoleViewModel;
import com.artisan.admin.resultModels.MessageBase;
import com.artisan.admin.resultModels.roleGroupResultModels.RoleGroupResultModel;
import com.artisan.admin.resultModels.roleResultModels.RoleMenuResultModel;
import com.artisan.admin.resultModels.roleResultModels.RoleResultModel;
import com.artisan.domain.dto.MenuDto;
import com.artisan.domain.dto.PageDto;
import com.artisan.domain.dto.RoleDto;
import com.artisan.domain.dto.RoleGroupDto;
import com.artisan.domain.serviceInterface.IMenuService;
import com.artisan.domain.serviceInterface.IRoleService;
import com.artisan.util.DateUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 角色控制器
 */
@RequestMapping("/api/role")
@RestController
@Api("角色模块")
@ApiOperation(value = "角色模块")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;

    /**
     * 获得列表
     */
    // GET /list
    @ApiOperation(value = "获得列表")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    paramType = "query",
                    name = "pageIndex",
                    dataType = "Int",
                    required = true,
                    value = "当前页，从0开始",
                    defaultValue = "0"),
            @ApiImplicitParam(
                    paramType = "query",
                    name = "pageSize",
                    dataType = "Int",
                    required = true,
                    value = "每页数",
                    defaultValue = "10")
    })
    @ApiResponses(@ApiResponse(code = 200, response = RoleResultModel.class, message = "成功"))
    @RequestMapping(
            value = {"/list"},
            method = {RequestMethod.GET})
    public MessageBase getList(@RequestParam(value = "pageIndex") int pageIndex,
                               @RequestParam(value = "pageSize") int pageSize) {
        MessageBase result = new MessageBase();
        PageDto<RoleDto> page = this.roleService.findList(pageIndex, pageSize);
        result.setPageIndex(page.getNumber());
        result.setPageSize(page.getSize());
        result.setTotalRecord(Math.toIntExact(page.getTotalElements()));

        List<RoleResultModel> models = new ArrayList<>();

        page.getContent().forEach(
                dto -> {
                    RoleResultModel model = new RoleResultModel();
                    model.setId(dto.getId());
                    model.setName(dto.getName());
                    model.setRoleGroupName(dto.getRoleGroupName());
                    model.setAddDate(DateUtil.timeStamp2Date(dto.getAddDate(), "", true));

                    models.add(model);
                });

        result.setData(models);
        return result;
    }

    /**
     * 获得详情
     *
     * @param id id
     */
    // GET /{1}
    @ApiOperation(value = "获得详情")
    @ApiResponses(@ApiResponse(code = 200, response = RoleResultModel.class, message = "成功"))
    @RequestMapping(value = {"/{id}"}, method = {RequestMethod.GET})
    public MessageBase get(@PathVariable int id) {
        MessageBase result = new MessageBase();
        RoleDto dto = this.roleService.find(id);
        RoleResultModel model = new RoleResultModel();
        model.setId(dto.getId());
        model.setName(dto.getName());
        model.setRoleGroupName(dto.getRoleGroupName());

        result.setData(model);
        return result;
    }

    /**
     * 更新数据
     *
     * @param model 数据
     */
    // PUT /
    @ApiOperation(value = "更新数据")
    @ApiResponses(@ApiResponse(code = 200, response = MessageBase.class, message = "成功"))
    @RequestMapping(value = {"/{id}"}, method = {RequestMethod.PUT})
    public MessageBase put(@PathVariable int id, @RequestBody RoleViewModel model) {
        MessageBase result = new MessageBase();
        RoleDto dto = new RoleDto();
        dto.setId(id);
        dto.setName(model.getName());
        dto.setRoleGroupId(model.getRoleGroupId());

        boolean b = this.roleService.update(dto);
        result.setSuccess(b);
        return result;
    }

    /**
     * 删除
     *
     * @param id id
     */
    // DELETE /{1}
    @ApiOperation(value = "删除")
    @ApiResponses(@ApiResponse(code = 200, response = MessageBase.class, message = "成功"))
    @RequestMapping(value = {"/{id}"}, method = {RequestMethod.DELETE})
    public MessageBase delete(@PathVariable int id) {
        MessageBase result = new MessageBase();
        boolean b = this.roleService.delete(id);
        result.setSuccess(b);
        return result;
    }

    /**
     * 获得权限状态列表
     *
     * @param id id
     */
    // GET /menuList
    @ApiOperation(value = "获得权限状态列表")
    @ApiResponses(@ApiResponse(code = 200, response = RoleMenuResultModel.class, message = "成功"))
    @RequestMapping(value = {"/menuList/{id}"}, method = {RequestMethod.GET})
    public MessageBase getMenuList(@PathVariable int id) {
        MessageBase result = new MessageBase();
        RoleDto dto = this.roleService.find(id);
        String[] ms = dto.getMenuIds().split(",");
        int[] ids = Arrays.stream(ms).mapToInt(Integer::parseInt).toArray();

        List<MenuDto> menus1 = this.menuService.findList(ids);
        List<RoleMenuResultModel> models = new ArrayList<>();
        menus1.forEach(m->{
            RoleMenuResultModel model1 = new RoleMenuResultModel();
            model1.setMenuId(m.getId());
            model1.setMenuName(m.getName());
            model1.setMenuParentId(m.getParentId());
            model1.setState(true);
            models.add(model1);
        });

        List<MenuDto> menus = this.menuService.findList();
        menus.removeAll(menus1);
        menus.forEach(m->{
            RoleMenuResultModel model1 = new RoleMenuResultModel();
            model1.setMenuId(m.getId());
            model1.setMenuName(m.getName());
            model1.setMenuParentId(m.getParentId());
            model1.setState(false);
            models.add(model1);
        });

        result.setData(models);
        return result;

    }

    /**
     * 修改权限
     * @param ids 菜单权限ids,用逗号隔开
     */
    // PATCH /menu
    @ApiOperation(value = "修改权限")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    paramType = "path",
                    name = "id",
                    dataType = "Int",
                    required = true,
                    value = "id",
                    defaultValue = "1"),
            @ApiImplicitParam(
                    paramType = "query",
                    name = "ids",
                    dataType = "Int",
                    required = true,
                    value = "菜单权限ids",
                    defaultValue = "1,2,3,4,5")
    })
    @ApiResponses(@ApiResponse(code = 200, response = RoleMenuResultModel.class, message = "成功"))
    @RequestMapping(value = {"/menu/{id}"}, method = {RequestMethod.PATCH})
    public MessageBase patchMenu(@PathVariable int id, @RequestBody String ids){
        MessageBase result = new MessageBase();
        boolean b = this.roleService.update(id, ids);
        result.setSuccess(b);
        return result;
    }
}
